package com.tensquare.article.filter;
/*
 *ClassName:JwtFilter
 *Description:拦截器类
 *@author:可爱的大鸭子
 */

import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import util.JwtUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class JwtFilter extends HandlerInterceptorAdapter {

    /*postHandle：返回model前执行
    * afterCompletion：返回model后执行*/


    @Autowired
    private JwtUtil jwtUtil;

    //在一个请求进入Controller层方法执行前执行这个方法
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler)
            throws Exception {
        System.out.println("经过了拦截器");
        /*无论如何都应该放行，具体能不能操作还需要在具体的操作中去判断
        * 拦截器只是负责把头请求的中包含token的令牌进行一个验证*/
        String authHeader=request.getHeader("X-Token");

        if (authHeader != null &&!authHeader.equals("undefined")) {
            final String token = authHeader; // The part after "Bearer "
            Claims claims = jwtUtil.parseJWT(token);
            if (claims != null) {
                try{
                    if("admin".equals(claims.get("roles"))){//如果是管理员
                        request.setAttribute("admin_claims", claims);
                    }
                    if("user".equals(claims.get("roles"))){//如果是用户
                        request.setAttribute("user_claims", claims);
                    }
                }catch (Exception e){
                    throw new RuntimeException("令牌有误");
                }
            }
        }
        return true;
    }
}
